package com.dn.lotte.ui.mainFragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dn.lotte.R;
import com.dn.lotte.api.ServerApi;
import com.dn.lotte.api.UserCenterServerApi;
import com.dn.lotte.bean.EventBusBean;
import com.dn.lotte.bean.NewHistoryBean;
import com.dn.lotte.bean.NoticeBean;
import com.dn.lotte.bean.PurchaseBean;
import com.dn.lotte.bean.TimeBean;
import com.dn.lotte.bean.WonderfulBannerBean;
import com.dn.lotte.ui.purchase.activity.PurchaseDetailActivity;
import com.dn.lotte.ui.usercenter.activity.BettingActivity;
import com.dn.lotte.ui.usercenter.activity.MessageActivity;
import com.dn.lotte.ui.usercenter.activity.MessageFragmentActivity;
import com.dn.lotte.ui.usercenter.activity.NumberRecordActivity;
import com.dn.lotte.ui.usercenter.activity.Top_up_recharge_Activity;
import com.dn.lotte.ui.usercenter.activity.WithdrawalActivity;
import com.dn.lotte.ui.wonderful.activity.DiscountsActivity;
import com.dn.lotte.ui.wonderful.activity.MoregameActivity;
import com.dn.lotte.ui.wonderful.adapter.SelectAdapter;
import com.dn.lotte.utils.AutoScrollTextView;
import com.dn.lotte.utils.CommonUtils;
import com.dn.lotte.utils.GlideImageLoader;
import com.easy.common.base.BaseFragment;
import com.easy.common.commonutils.SPUtils;
import com.easy.common.commonutils.StringUtils;
import com.easy.common.commonwidget.DnToolbar;
import com.easy.common.commonwidget.RippleView;
import com.google.android.flexbox.FlexboxLayout;
import com.lzy.okgo.model.HttpParams;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;


/**
 * 0511358616
 * 13844588185
 * 精彩推荐
 */
public class WonderfulFragment extends BaseFragment implements
        RippleView.OnRippleCompleteListener, DnToolbar.OnRightTitleClickListener, DnToolbar.OnLeftTitleClickListener {

    @Bind(R.id.lt_main_title_left)
    TextView ltMainTitleLeft;
    @Bind(R.id.lt_main_title)
    TextView ltMainTitle;
    @Bind(R.id.lt_main_title_right)
    TextView ltMainTitleRight;
    @Bind(R.id.toolbar)
    DnToolbar mToolbar;
    @Bind(R.id.banner)
    Banner mBanner;
    @Bind(R.id.remark)
    ImageView remark;
    @Bind(R.id.fcdtext)
    AutoScrollTextView fcdtext;
    @Bind(R.id.rl_quickly)
    RippleView mQuickly;
    @Bind(R.id.rl_withdrawals)
    RippleView mWithdrawals;
    @Bind(R.id.rl_etting)
    RippleView mEtting;
    @Bind(R.id.rl_number)
    RippleView mNumber;
    @Bind(R.id.tv_new)
    TextView tvNew;
    @Bind(R.id.rl)
    RelativeLayout rl;
    @Bind(R.id.fl_new_number)
    FlexboxLayout mFlexboxLayout;
    @Bind(R.id.tv)
    TextView tv;
    @Bind(R.id.rl_more_game)
    RippleView mMoreGame;
    @Bind(R.id.recyclerView)
    RecyclerView mRecyclerView;
    private List<PurchaseBean.TableBean> mSelectData = new ArrayList<>();
    private SelectAdapter mMSelectAdapter;
    private EventBusBean<List<PurchaseBean.TableBean>> dataBean;
    private List<WonderfulBannerBean.TableBean> mlist = new ArrayList<>();
    private List<String> images = new ArrayList<>();
    private List<String> titles = new ArrayList<>();
    private ArrayList<String> titleList = new ArrayList<String>();
    private List<NoticeBean.TableBean> mmessagelist = new ArrayList<>();
    private String messagetype="";

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_wonderful;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    protected void initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        mToolbar.setMainTitle("开心娱乐");
        mToolbar.setToolbarRightBackImageRes(R.drawable.message);
        mToolbar.setOnRightTitleClickListener(this);
        mToolbar.setToolbarLeftBackImageRes(R.drawable.youhui);
        mToolbar.setOnLeftTitleClickListener(this);
        mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3, LinearLayoutManager.VERTICAL, false));
        mRecyclerView.setNestedScrollingEnabled(false);
        mMSelectAdapter = new SelectAdapter(R.layout.item_wonderful_select, mSelectData);
        if (SPUtils.getSharedStringData(getActivity(), "FIRSTLOGIN").equals("1")) {
            if (CommonUtils.getMoreGameList() != null) {
                mSelectData = CommonUtils.getMoreGameList();
                mMSelectAdapter.setNewData(mSelectData);
            }
        } else {
            SPUtils.setSharedStringData(getActivity(), "FIRSTLOGIN", "1");
            loadData2();

        }
//        if (CommonUtils.getMoreGameList() != null){
//            mSelectData = CommonUtils.getMoreGameList();
//            mMSelectAdapter.setNewData(mSelectData);
//        }else {
//            loadData2();
//        }


        mRecyclerView.setAdapter(mMSelectAdapter);
        loadBannerData();
        mQuickly.setOnRippleCompleteListener(this);
        mMoreGame.setOnRippleCompleteListener(this);
        mWithdrawals.setOnRippleCompleteListener(this);
        mEtting.setOnRippleCompleteListener(this);
        mNumber.setOnRippleCompleteListener(this);
        mMSelectAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putString("id", mSelectData.get(position).getId());
                bundle.putString("title", mSelectData.get(position).getTitle());
                startActivity(PurchaseDetailActivity.class, bundle);
            }
        });

        fcdtext.setOnItemClickListener(new AutoScrollTextView.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Intent intent = new Intent(getActivity(), MessageFragmentActivity.class);
                intent.putExtra("details", mmessagelist.get(position));
                startActivity(intent);
                //  Toast.makeText(getActivity(), "position : " + position, Toast.LENGTH_SHORT).show();
            }
        });
        loadData();
        //定时刷新 站内信
        getMoney();
    }

    private void loadData2() {
        ServerApi.getPurchaseData()
                .map(new Function<PurchaseBean, List<PurchaseBean.TableBean>>() {
                    @Override
                    public List<PurchaseBean.TableBean> apply(@NonNull PurchaseBean purchaseBean) throws Exception {
                        List<PurchaseBean.TableBean> allBeanList = purchaseBean.getTable();
                        Log.i("DNlog", allBeanList.size() + "-----------");
                        return allBeanList;
                    }
                })
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<PurchaseBean.TableBean>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull List<PurchaseBean.TableBean> list) {
                        if (list != null && list.size() > 8) {
                            for (PurchaseBean.TableBean bean : list){
                                if(bean.getTitle().equals("重庆时时彩")||
                                        bean.getTitle().equals("腾讯分分彩")||
                                        bean.getTitle().equals("菲律宾1.5分") ||
                                        bean.getTitle().equals("北京PK10") ||
                                        bean.getTitle().equals("广东11选5") ||
                                        bean.getTitle().equals("新德里1.5分彩") ||
                                        bean.getTitle().equals("英国60秒赛车") ||
                                        bean.getTitle().equals("福彩3D") )
                                {
                                    mSelectData.add(bean);
                                }
                            }
//                            mSelectData = list.subList(0, 6);
                            mMSelectAdapter.setNewData(mSelectData);
                            CommonUtils.setMoreGameList(mSelectData);
                        }

                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    private void loadData() {
        HttpParams httpParams = new HttpParams();
        httpParams.put("page", "1");
        httpParams.put("pagesize", "1000");
        ServerApi.getNoticeData(httpParams)
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
//                        startProgressDialog();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NoticeBean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull NoticeBean purchaseBean) {
                        if (purchaseBean.getResult().equals("1")) {
                            Log.i("DNlog", purchaseBean.getTable().size() + "");
                            if (purchaseBean.getResult().equals("1")) {
                                for (int i = 0; i < purchaseBean.getTable().size(); i++) {
                                    titleList.add(purchaseBean.getTable().get(i).getTitle());
                                    mmessagelist.add(purchaseBean.getTable().get(i));
                                }
                                if (fcdtext != null) fcdtext.setTextList(titleList);
                            }
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {
//                        stopProgressDialog();
                    }
                });
    }

    private void loadBannerData() {
        ServerApi.getWonderfulBannerData().doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(@NonNull Disposable disposable) throws Exception {
            }
        })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<WonderfulBannerBean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull WonderfulBannerBean wonderfulBannerBean) {
                        if (wonderfulBannerBean.getResult().equals("1")) {
                            mlist = wonderfulBannerBean.getTable();
                            images.clear();
                            titles.clear();
                            for (WonderfulBannerBean.TableBean tableBean : mlist) {
                                images.add("http://" + tableBean.getUrl());
                                titles.add(tableBean.getTitle());
                            }
                            initBanner();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                    }
                });
        ServerApi.getNewHistoryData().doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(@NonNull Disposable disposable) throws Exception {
            }
        })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NewHistoryBean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull NewHistoryBean newHistoryBean) {
                        if (newHistoryBean.getResult().equals("1")) {
                            List<NewHistoryBean.TableBean> table = newHistoryBean.getTable();
                            if (table != null && table.size() > 0) {
                                String number = table.get(0).getNumber();
                                showlabel(mFlexboxLayout, number);
                            }
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                    }
                });

    }

    /**
     * 显示标签
     *
     * @param flexboxLayout FlexboxLayout
     * @param str           “聪明，强，无敌” --> 以 ，隔开的字符串
     */
    private void showlabel(FlexboxLayout flexboxLayout, String str) {
        if (flexboxLayout != null) {
            flexboxLayout.removeAllViews();
            String[] allStr;
            if (!StringUtils.isEmpty(str)) {
                allStr = str.split(",");
                for (int i = 0; i < allStr.length; i++) {
                    TextView textView = new TextView(getActivity());
                    textView.setText(allStr[i]);
                    textView.setGravity(Gravity.CENTER);
                    textView.setTextSize(16);
                    textView.setTextColor(getResources().getColor(R.color.T5));
                    textView.setBackgroundResource(R.drawable.round_white);
                    flexboxLayout.addView(textView);
                    ViewGroup.LayoutParams params = textView.getLayoutParams();
                    if (params instanceof FlexboxLayout.LayoutParams) {
                        FlexboxLayout.LayoutParams layoutParams = (FlexboxLayout.LayoutParams) params;
                        layoutParams.setMargins(30, 40, 0, 0);
                        textView.setLayoutParams(layoutParams);
                    }
                }
            }
        }
    }

    @Override
    public void onComplete(RippleView rippleView) {
        switch (rippleView.getId()) {
            case R.id.rl_more_game:
                //自定义游戏
                startActivity(MoregameActivity.class);
                break;
            case R.id.rl_quickly:
                //充值
                Intent intent = new Intent(getActivity(), Top_up_recharge_Activity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                startActivity(intent);
                break;
            case R.id.rl_withdrawals:
                //提现
                Intent intents = new Intent(getActivity(), WithdrawalActivity.class);
                intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                startActivity(intents);
                break;
            case R.id.rl_etting:
                //投注记录
                startActivity(BettingActivity.class);
                break;
            case R.id.rl_number:
                //追号记录
                startActivity(NumberRecordActivity.class);
                break;
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMainEventBus(EventBusBean<List<PurchaseBean.TableBean>> bean) {
        if ("SelectDataToWonder".equals(bean.getTag())) {
            this.dataBean = bean;
            mSelectData = bean.getData();
            mMSelectAdapter.setNewData(mSelectData);

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void initBanner() {
//        Integer[] images={R.drawable.a,R.drawable.b,R.drawable.c};
//        images.add("https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=672768704,554459686&fm=27&gp=0.jpg");
//        images.add("https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1437196005,2049634259&fm=11&gp=0.jpg");
//        images.add("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=4240575310,77541553&fm=11&gp=0.jpg");
//        Log.i("Dnlog", images.get(0) + "");
        if (mBanner != null) {
            //设置banner样式
            mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
            //设置图片加载器
            mBanner.setImageLoader(new GlideImageLoader());
            //设置图片集合
            mBanner.setImages(images);
            //设置banner动画效果
            mBanner.setBannerAnimation(Transformer.Accordion);
            //设置标题集合（当banner样式有显示title时）
            mBanner.setBannerTitles(titles);
            //设置自动轮播，默认为true
            mBanner.isAutoPlay(true);
            //设置轮播时间
            mBanner.setDelayTime(2500);
            //设置指示器位置（当banner模式中有指示器时）
            mBanner.setIndicatorGravity(BannerConfig.RIGHT);
            //banner设置方法全部调用完毕时最后调用
            //banner设置方法全部调用完毕时最后调用
            mBanner.start();
        }

    }


    @Override
    public void onRightClick(View view) {
        startActivity(MessageActivity.class);
        if(mToolbar!=null)
        mToolbar.setToolbarRightBackImageRes(R.drawable.message);
    }

    @Override
    public void onLeftClick(View view) {
        startActivity(DiscountsActivity.class);
//        mToolbar.setToolbarRightBackImageRes(R.drawable.message2);
    }

    @Override
    public void onResume() {
        super.onResume();
        fcdtext.startAutoScroll();
    }

    @Override
    public void onPause() {
        super.onPause();
        fcdtext.stopAutoScroll();
    }

    public void getMoney() {
        final Handler handler = new Handler();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
// TODO Auto-generated method stub
// 在此处添加执行的代码
                Log.e("kdkkd", "dkkdkd");
                requestMoney();
                handler.postDelayed(this, 20000);// 50是延时时长
            }
        };
        handler.postDelayed(runnable, 20000);// 打开定时器，执行操作
        // handler.removeCallbacks(runnable);// 关闭定时器处理
    }

    private void requestMoney() {
        UserCenterServerApi.getMoney()
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        startProgressDialog();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<TimeBean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        stopProgressDialog();
                    }

                    @Override
                    public void onNext(@NonNull TimeBean timeBean) {
                        stopProgressDialog();
                      if (timeBean.getResult().equals("1")){
                            //里面有一个Email字段 有多少的意思就是表示有多少条
                          if (!timeBean.getEmail().equals(messagetype)){
                              messagetype=timeBean.getEmail();
                              if(mToolbar!=null)
                              mToolbar.setToolbarRightBackImageRes(R.drawable.message2);
                          }
                      }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        stopProgressDialog();

                    }

                    @Override
                    public void onComplete() {
                        stopProgressDialog();

                    }
                });
    }

}
